const util = require("../../utils/util.js");
const api = require("../../config/api.js");
const user = require("../../utils/user.js");
// const timer = require("../../utils/wxTimer.js");
let leftHeight = 0,
  rightHeight = 0; //分别定义左右两边的高度
let query;
//获取应用实例
const app = getApp();

Page({
  data: {
    newGoods: [],
    hotGoods: [],
    salesGoods: [],
    topics: [],
    brands: [],
    groupons: [],
    floorGoods: [],
    banner: [],
    channel: [],
    coupon: [],
    goodsCount: 0,
    search_icon: "../../static/images/icon-search.png",
    leftList: [],
    rightList: [],
    hotsellWord: '热卖专区',
    limitDiscount:'限时优惠',
    bgSrc: '',
    countdown: '',
    endDate2: '2022/01/15 19:00:00',
    wxTimerList: {},
    adShow: false,
    adPic: 'https://yigongyun-test.oss-cn-shenzhen.aliyuncs.com/ad.png',
    couponId: null
  },

  onShareAppMessage: function() {
    return {
      title: '疆禾农礼',
      desc: '疆禾农礼商城',
      path: '/pages/index/index'
    }
  },
  async isLeft() {
    let that = this;
    const { hotGoods, leftList, rightList } = this.data;
    query = wx.createSelectorQuery();
    for (const item of that.data.hotGoods) {
      leftHeight <= rightHeight ? leftList.push(item) : rightList.push(item); //判断两边高度，来觉得添加到那边
      await this.getBoxHeight(leftList, rightList);
    }
  },
  getBoxHeight(leftList, rightList) {
    let that=this
    //获取左右两边高度
    
    return new Promise((resolve, reject) => {
      that.setData({ leftList, rightList }, () => {
        setTimeout(() => { 
        query.select("#left").boundingClientRect();
        query.select("#right").boundingClientRect();
        query.exec((res) => {
          leftHeight = res[0].height; //获取左边列表的高度
          rightHeight = res[1].height; //获取右边列表的高度
          resolve();
        });
      },50);
    })
    });
 
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading(); //在标题栏中显示加载
    this.getIndexData();
    wx.hideNavigationBarLoading(); //完成停止加载
    wx.stopPullDownRefresh(); //停止下拉刷新
  },

  getIndexData: function () {
    let that = this;
    util.request(api.IndexUrl).then(function (res) {
      let banners = res.data.banner;
      banners.forEach(element => {
        if(element.link.indexOf('-') >= 0){
          element.type = element.link.split('-')[0];
          element.link = element.link.split('-')[1];
        }else{
          element.type = 'goods';
        }
      });
      if (res.errno === 0) {
        that.setData({
          newGoods: res.data.newGoodsList,
          hotGoods: res.data.hotGoodsList,
          topics: res.data.topicList,
          brands: res.data.brandList,
          floorGoods: res.data.floorGoodsList,
          banner: banners,
          groupons: res.data.grouponList,
          channel: res.data.channel,
          coupon: res.data.couponList,
          tuijian: res.data.tuijian,
          salesGoods: res.data.salesGoodsList,
          endDate2: res.data.endDate,
          leftList: [],
          rightList: []
        });
        if(res.data.couponList.length > 0){
          that.setData({
            adShow: true, 
            adPic: res.data.couponList[0].tag,
            couponId: res.data.couponList[0].id
          });
        }
        if(res.data.bgSrc){
          that.setData({bgSrc: res.data.bgSrc})
        }
        if(res.data.hotsellWord){
          that.setData({hotsellWord: res.data.hotsellWord})
        }
        that.isLeft();
      }
    });
    util.request(api.GoodsCount).then(function (res) {
      that.setData({
        goodsCount: res.data,
      });
    });
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    if (options.scene) {
      //这个scene的值存在则证明首页的开启来源于朋友圈分享的图,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      var scene = decodeURIComponent(options.scene);
      console.log("scene:" + scene);

      let info_arr = [];
      info_arr = scene.split(",");
      let _type = info_arr[0];
      let id = info_arr[1];

      if (_type == "goods") {
        wx.navigateTo({
          url: "../goods/goods?id=" + id,
        });
      } else if (_type == "groupon") {
        wx.navigateTo({
          url: "../goods/goods?grouponId=" + id,
        });
      } else {
        wx.navigateTo({
          url: "../index/index",
        });
      }
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.grouponId) {
      //这个pageId的值存在则证明首页的开启来源于用户点击来首页,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: "../goods/goods?grouponId=" + options.grouponId,
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.goodId) {
      //这个goodId的值存在则证明首页的开启来源于分享,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: "../goods/goods?id=" + options.goodId,
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.orderId) {
      //这个orderId的值存在则证明首页的开启来源于订单模版通知,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: "../ucenter/orderDetail/orderDetail?id=" + options.orderId,
      });
    }
    this.getIndexData();
    //定时器
    this.countTime();
  },
  onReady: function () {
    
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  getCoupon(e) {
    let couponId = e.currentTarget.dataset.index;
    util
      .request(
        api.CouponReceive,
        {
          couponId: couponId,
        },
        "POST"
      )
      .then((res) => {
        if (res.errno === 0) {
          wx.showToast({
            title: "领取成功",
          });
        } else {
          util.showErrorToast(res.errmsg);
        }
      });
  },
  getCouponAndCloseOverlay(e){
    this.getCoupon(e);
    this.closeOverlay();
  },
  closeOverlay(){
    this.setData({
      adShow: false
    })
  },
  countTime() {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(that.data.endDate2);//设置截止时间
    var end = endDate.getTime();
    var leftTime = end - now; //时间差                              
    var d, h, m, s, ms;
    if (leftTime >= 0) {
      d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
      s = s < 10 ? "0" + s : s
      m = m < 10 ? "0" + m : m
      h = h < 10 ? "0" + h : h
      that.setData({
        countdown: d + "天 " + h + ":" + m + ":" + s,
      })
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 100);
    } else {
      console.log('已截止')
      that.setData({
        countdown: '00:00:00'
      })
    }
  },
});
